<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="auto"
    status-icon
  >
    <el-row :gutter="gutter">
      <template v-for="(item, index) in columns" :key="index">
        <el-col :span="item.span || span">
          <el-form-item :label="item.label" :prop="item.prop" :style="item.style">
            <!-- 普通输入组件 -->
            <component
              v-if="!item.options"
              :is="item.component"
              v-model="formData[item.prop]"
              v-bind="item.componentProps || {}"
              @change="item.onChange"
              style="width: 100%;"
            />
            
            <!-- 选择器组件 -->
            <el-select
              v-else
              v-model="formData[item.prop]"
              :placeholder="item.placeholder || `请选择${item.label}`"
              :clearable="item.clearable !== false"
              v-bind="item.componentProps || {}"
              style="width: 100%"
            >
              <el-option
                v-for="opt in item.options"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
                :disabled="opt.disabled"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </template>
      <slot />
    </el-row>

    <div v-if="showActions" class="active-btn" style="display: flex; justify-content: flex-end;">
      <el-button @click="handleReset">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </div>
  </el-form>
</template>

<script setup>
import { ref } from 'vue'

const props = defineProps({
  columns: {
    type: Array,
    required: true,
    validator: (value) => {
      return value.every(item => {
        const valid = 'label' in item && 'prop' in item
        // 如果有options，可以不需要component
        return valid && (item.options || 'component' in item)
      })
    }
  },
  rules: {
    type: Object,
    default: () => ({})
  },
  formData: {
    type: Object,
    required: true
  },
  span: {
    type: Number,
    default: 12
  },
  gutter: {
    type: Number,
    default: 20
  },
  showActions: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const formRef = ref()
const emit = defineEmits(['submit', 'reset'])

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    emit('submit', props.formData)
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

const handleReset = () => {
  formRef.value?.resetFields()
  emit('reset')
}
</script>